<?php
/*
+------------------------------------------------------------------------------+
| Copyright (c) 2009, COPEO                                          |
| All rights reserved.                                                         |
|                                                                              |
| Redistribution and use in source and binary forms, with or without           |
| modification, are permitted provided that the following conditions are met:  |
|     * Redistributions of source code must retain the above copyright         |
|       notice, this list of conditions and the following disclaimer.          |
|     * Redistributions in binary form must reproduce the above copyright      |
|       notice, this list of conditions and the following disclaimer in the    |
|       documentation and/or other materials provided with the distribution.   |
|     * Neither the name of the <organization> nor the                         |
|       names of its contributors may be used to endorse or promote products   |
|       derived from this software without specific prior written permission.  |
|                                                                              |
| THIS SOFTWARE IS PROVIDED BY draftrack team ''AS IS'' AND ANY                |
| EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED    |
| WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE       |
| DISCLAIMED. IN NO EVENT SHALL draftrack team BE LIABLE FOR ANY               |
| DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES   |
| (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
| LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND  |
| ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   |
| (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS|
| SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                 |
+------------------------------------------------------------------------------+
*/
/*
* Front end plugin extension to manage application initialization
*/
require_once('Zend/Controller/Plugin/Abstract.php');

/**
 * Plugin d'initialisation
 * 
 * @uses Zend_Controller_Plugin_Abstract
 */
class Myzen_Controller_Plugin_Config extends Zend_Controller_Plugin_Abstract
{

    
  /**
   * Constructor
   *
   * @param  void
   * @return void
  **/
	public function __construct()
	{
    	// configuration initialization
    	$this->_initConfig();
	}
	

  protected function _initConfig() {

	//we are trying to load the conf, may not work if ENVIRONMENT badly set
	//No need to catch the error has this is mandatory stuff	//$app_config = new Zend_Config_Xml('config/main.xml', 'production',true);
	//do not change, use in other files
	$env = getenv("ZF_ENV");
	if(empty($env)) $env = 'production';
	
	$app_config = new Zend_Config_Ini('../app/config/config.ini', $env,true);


	//We check if some passwords are not defined in the secret.ini file
	if(is_file('../app/config/secret.ini')) {
		$app_config_secret = new Zend_Config_Ini('config/secret.ini', $env);
		$app_config->merge($app_config_secret);
	}




	//First, we check if we can display the app or if the app is under maintenance and cannot be displayed
	if($app_config->masterSwitch->takeOffline == true)
	{
		//we send an header 503 to tell the client that the app is under maintenance
		header("HTTP/1.1 503 Service Unavailable");
		echo 'Sorry the application is not available while we are doing voodoo things';
		exit;	
	}	

/*	
	//set the error reporting, should be turned off for production setting none
	if($app_config->php_error_report == 'all') {
		error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
		ini_set("display_errors", 1);
		ini_set('display_startup_errors', 1);
	}
	else if($app_config->php_error_report == 'none') {
		error_reporting(0);
		ini_set("display_errors", 0);
		ini_set('display_startup_errors', 0);
	}
	//Prefer setting by default to the stricter one
	else {
		error_reporting(E_ERROR | E_WARNING);
		ini_set("display_errors", 0);
		ini_set('display_startup_errors', 0);
	}
*/
	//We register it so we are sure it is available everywhere
	//Now we have the registry, we can register our config file for global access 
	Zend_Registry::set('app_config', $app_config);
			

  } //end initConfig
  
  
  //WHen the route is shut down, we know the module and may load a specific config file
  public function routeShutdown(Zend_Controller_Request_Abstract $request) 
	{
		//now we should be safe to look for motential routing
		$app_config = Zend_Registry::get('app_config');
		$moduleName = $request->getParam('module');

		$potentialConf = ROOT_PATH.'/app/src/modules/'.$moduleName.'/config.ini';
		if(is_file($potentialConf)) {
			//User defined some special routes for the module, we try loading them	
			Zend_Registry::get('app_log')->log('loading custom config for module '.$moduleName,Zend_Log::DEBUG);
			
			//environment variable to check what needs to be loaded
			$env = getenv("ZF_ENV");
			if(empty($env)) $env = 'production';
			
			$front = Zend_Controller_Front::getInstance(); 
			$router = $front->getRouter();
			
			//We may have an issue on a route if the environment is not production in this case, we fallback on production one
			try{
				$config = new Zend_Config_Ini($potentialConf, $env);
			} catch(Zend_Config_Exception $e) {
				if('production' != $env) {
					Zend_Registry::get('app_log')->log('environment  '.$env.' not defined on config file, fallbacking to production one',Zend_Log::DEBUG);
					$config = new Zend_Config_Ini($potentialConf, 'production');
				} else {
					Zend_Registry::get('app_log')->log('Route ini file badly formatted for '.$potentialConf,Zend_Log::CRIT);
					require_once(Zend/Config/Exception.php);
					throw new Zend_Config_Exception($e->getMessage());	
				}
			}
			
			
			$app_config->merge($config);
			
				
		} //end is file potential config
		
		//No more update allowed on the config after this point
		$app_config->setReadOnly();
		
	} //end route shutdown
  

} // end initialization helper